<template>
  <div class="sentence-practice">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/english" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">长难句训练</h5>
    </div>

    <!-- 句子卡片 -->
    <div class="sentence-card">
      <!-- NPC分析工具栏 -->
      <div class="analysis-toolbar">
        <button
            v-for="tool in tools"
            :key="tool.type"
            class="tool-btn"
            :class="{ active: currentTool === tool.type }"
            @click="selectTool(tool.type)"
        >
          {{ tool.label }}
        </button>
      </div>

      <!-- 提示信息 -->
      <div class="selection-tip mb-3 text-muted">
        <i class="bi bi-info-circle"></i>
        {{ selectionTip }}
      </div>

      <!-- 句子文本 -->
      <div class="sentence-text" ref="practiceText">
        <span
            v-for="(word, index) in words"
            :key="index"
            class="word"
            :class="word.classes"
            @mousedown="startSelection($event, index)"
            @mousemove="updateSelection($event, index)"
            @mouseup="endSelection"
        >{{ word.text }}{{ word.suffix }}</span>
      </div>

      <button class="check-answer-btn" @click="showAnalysis">检查答案</button>

      <!-- 答案解析部分 -->
      <div class="analysis-section" v-show="showingAnalysis">
        <h6 class="mb-3">NPC分析</h6>
        <div class="npc-analysis">
          <div
              class="npc-item"
              v-for="(item, index) in npcAnalysis"
              :key="index"
          >
            <span
                :class="['npc-label', `${item.type}-label`]"
            >{{ item.label }}</span>
            <div v-if="item.arrytype === 'array'">

              <ul>
                <li
                    v-for="(contents, index) in item.content"
                    :key="index"
                >
                  {{ contents }}
                </li>
              </ul>
            </div>
            <div v-if="item.arrytype === 'single'">
              {{ item.content }}
            </div>

<!--            {{ item.content }}-->
          </div>
        </div>

        <div class="structure-analysis">
<!--          <h6 class="mb-2">句子结构</h6>-->
          <p style="font-weight: bold;">句子类型：</p>
          <p>{{ structureAnalysis.main }}</p>
          <p style="font-weight: bold;">难点分析：</p>
          <p>{{ structureAnalysis.child }}</p>
          <p style="font-weight: bold;">要点分析：</p>
          <ul>
            <li
                v-for="(modifier, index) in structureAnalysis.modifiers"
                :key="index"
            >
              {{ modifier }}
            </li>
          </ul>
        </div>

        <div class="translation">
          <h6 class="mb-2">参考译文</h6>
          <p>{{ translation }}</p>
        </div>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-tools">
      <div class="progress progress-bar">
        <div class="progress-bar bg-success" :style="{ width: progress + '%' }"></div>
      </div>
      <div class="d-flex justify-content-between align-items-center">
        <div class="text-muted">{{ currentQuestionIndex+1 }}/{{ totalQuestions }}</div>
        <button class="btn-next" @click="nextSentence"  :disabled="currentQuestionIndex+1 === totalQuestions">
          下一句 <i class="bi bi-arrow-right"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import http from "@/router/http";
import router from "@/router";

export default {
  name: 'SentencePracticeView',

  data() {
    return {
      currentTool: null,
      isSelecting: false,
      startWordIndex: null,
      showingAnalysis: false,
      currentIndex: 3,
      totalQuestions: 10,
      currentQuestionIndex: 0,
      words: [],
      tools: [
        { type: 'noun', label: '主句' },
        // { type: 'phrase', label: '动词短语' },
        { type: 'clause', label: '从句' },
        { type: 'clear', label: '清除' }
      ],
      npcAnalysis: [],
      structureAnalysis: {
        main: '',
        child: '',
        modifiers: []
      },
      translation: ''
    };
  },

  computed: {
    progress() {
      return (this.currentIndex / this.totalQuestions) * 100;
    },
    selectionTip() {
      if (!this.currentTool) {
        return '请先选择要标记的类型，然后点击句子中的单词进行标记';
      }
      const typeText = {
        noun: '名词短语',
        phrase: '动词短语',
        clause: '从句'
      }[this.currentTool];
      return `请点击句子中的单词标记${typeText}`;
    }
  },

  created() {
    this.initializeText();
    this.fetchDataFromBackend();
  },

  methods: {
    initializeText() {
      const text = 'Despite the controversy surrounding its implementation, the new policy that aims to reduce carbon emissions has gained support from environmental groups worldwide.';
      this.words = text.match(/[\w']+|[.,!?;]|\s+/g).map(token => ({
        text: token.trim(),
        suffix: token.match(/\s+/)? ' ' : '',
        classes: {}
      }));
    },

    selectTool(type) {
      if (type === 'clear') {
        this.clearAllSelections();
        this.currentTool = null;
        return;
      }
      this.currentTool = this.currentTool === type? null : type;
    },

    clearAllSelections() {
      this.words.forEach(word => {
        const { selected,...rest } = word.classes;
        word.classes = selected? { selected } : {};
      });
    },

    startSelection(event, index) {
      if (!this.currentTool || this.currentTool === 'clear') return;
      this.isSelecting = true;
      this.startWordIndex = index;
      this.words[index].classes = { selected: true };
      event.preventDefault();
    },

    updateSelection(event, index) {
      if (!this.isSelecting) return;

      const start = Math.min(this.startWordIndex, index);
      const end = Math.max(this.startWordIndex, index);

      this.words.forEach((word, i) => {
        const currentClasses = {...word.classes };
        delete currentClasses.selected;
        word.classes = {
          ...currentClasses,
          selected: i >= start && i <= end
        };
      });
    },

    endSelection() {
      if (!this.isSelecting) return;

      this.words.forEach(word => {
        if (word.classes.selected) {
          const currentClasses = {...word.classes };
          delete currentClasses.selected;
          word.classes = {
            ...currentClasses,
            [this.currentTool]: true
          };
        }
      });

      this.isSelecting = false;
      this.startWordIndex = null;
    },

    showAnalysis() {
      this.showingAnalysis = true;
    },

    async nextSentence() {
      this.currentQuestionIndex++;
      await this.fetchDataFromBackend();
    },

    async fetchDataFromBackend() {
      try {
        const response = await http.get('/student/topNalysis/getLongDifficultSentenceInfo?currentQuestionIndex=' + this.currentQuestionIndex);
        const data = response.data;
        if (data && data.code === 1 && data.response) {
          if (data.response.subjectMatter) {
            const text = JSON.parse(data.response.subjectMatter);
            const keysArray = Object.keys(text);
            this.words = text[keysArray[0]].match(/[\w']+|[.,!?;]|\s+/g).map(token => ({
              text: token.trim(),
              suffix: token.match(/\s+/) ? ' ' : '',
              classes: {}
            }))
          }
          this.currentIndex = this.currentQuestionIndex+1;
          this.totalQuestions = data.response.totalNumber;
          if (data.response.analysis) {
            const analysisData = JSON.parse(data.response.analysis);
            const sentenceParse = analysisData["句子解析"];
            // 处理句子结构数据
            this.structureAnalysis.main = sentenceParse["要点分析"]["句子类型"];
            this.structureAnalysis.child = sentenceParse["要点分析"]["难点分析"];
            this.structureAnalysis.modifiers = sentenceParse["要点分析"]["要点分析"].concat(sentenceParse["要点分析"]["要点分析"]);
            // 处理NPC分析数据
            this.npcAnalysis = [];
            const mainP = sentenceParse["句子结构"];
            const keysArrayP = Object.keys(mainP);
            keysArrayP.forEach((main, index) => {
              this.npcAnalysis.push({
                type: 'point',
                label: main,
                content: mainP[main],
                arrytype: Array.isArray(mainP[main]) ? 'array' :'single'
              });
            });
            // 处理翻译数据
            this.translation = analysisData["中文翻译"];
            this.showingAnalysis = false;
          }
        } else {
          alert("暂无数据，请稍后再试");
          router.push("/english");
        }
      } catch (error) {
        console.error('获取长难句训练数据失败:', error);
      }
    },
  }
};
</script>

<style scoped>
.sentence-practice {
  background-color: #f0f9f9;
  padding-bottom: 70px;
  min-height: 100vh;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.sentence-card {
  background: white;
  border-radius: 15px;
  padding: 20px;
  margin: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.sentence-text {
  font-size: 1.1rem;
  line-height: 1.8;
  margin-bottom: 20px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.analysis-toolbar {
  background: white;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.tool-btn {
  padding: 8px 15px;
  border-radius: 20px;
  border: 1px solid #ddd;
  background: white;
  font-size: 0.9rem;
  cursor: pointer;
  text-align: center;
}

.tool-btn.active {
  background: #40e0d0;
  color: white;
  border-color: #40e0d0;
}

.word {
  cursor: pointer;
  padding: 0 2px;
  border-radius: 3px;
  display: inline-block;
  user-select: none;
}

.word.selected {
  background-color: rgba(255, 255, 255, 0.3);
  outline: 1px dashed #666;
}

.word.noun {
  background-color: rgba(255, 107, 107, 0.2);
  outline: 1px solid rgba(255, 107, 107, 0.4);
}

.word.phrase {
  background-color: rgba(74, 144, 226, 0.2);
  outline: 1px solid rgba(74, 144, 226, 0.4);
}

.word.clause {
  background-color: rgba(155, 89, 182, 0.2);
  outline: 1px solid rgba(155, 89, 182, 0.4);
}

.selection-tip {
  background: #f8f9fa;
  padding: 10px 15px;
  border-radius: 8px;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.check-answer-btn {
  background: #40e0d0;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 20px;
  margin-top: 15px;
  width: 100%;
}

.analysis-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-top: 15px;
}

.npc-analysis {
  margin: 15px 0;
}

.npc-item {
  margin-bottom: 10px;
  padding: 10px;
  background: white;
  border-radius: 6px;
}

.npc-label {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
  margin-right: 8px;
}

.noun-label {
  background: #FFE4E1;
  color: #FF6B6B;
}

.phrase-label {
  background: #E0FFFF;
  color: #4A90E2;
}

.clause-label {
  background: #E6E6FA;
  color: #9B59B6;
}

.structure-analysis {
  margin: 15px 0;
  padding: 10px;
  background: white;
  border-radius: 6px;
}

.translation {
  color: #666;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
}

.bottom-tools {
  position: fixed;
  bottom: 0;
  width: 100%;
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.progress-bar {
  height: 4px;
  margin-bottom: 15px;
}

.btn-next {
  background: #40e0d0;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 20px;
}

.btn-next:hover {
  background: #3bcdc0;
}
</style>